home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2229 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1011 b 

  1. Path: crl.crl.com!not-for-mail
  2. From: bobfry@crl.com (Robert Fry)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: 19 Jan 1996 15:10:19 -0800
  6. Organization: CRL Dialup Internet Access
  7. Message-ID: <4dp8cr$sit@crl.crl.com>
  8. References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>     <4dorr8$i58@cloner3.netcom.com> <ALUN.CHAMPION.96Jan19170141@g7240065.bridge.bst.bls.com>
  9. NNTP-Posting-Host: crl.com
  10.  
  11. Someone was asking for a quick way to determine if a number is a power of 
  12. 2. The solutions I've seen involved ounting every bit and seeing if the 
  13. number of 'on' bits is 1. But why not take advantage of the binary 
  14. representation of numbers and use:
  15.  
  16. int is_power_of_2( long num)
  17. {
  18.     return((( num - 1) & num) == 0);
  19. }
  20.  
  21. (You could also make a macro of it if you need better speed in exchange 
  22. for reduced maintainability):
  23.  
  24. #define IS_POWER_OF_2(num) (!(( num - 1) & num))
  25.  
  26. Be careful with this, of course. IS_POWER_OF_2(x++) has undefined results,
  27. for example.
  28.  
  29.   Bob
  30.